package com.gage.print.pdf.util;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.WriterException;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class WordTemplate {
	public static void genrateWordTemplate(OutputStream outputStream, String majorCode, String majorName)
			throws WriterException {
		try {
			String imgStr = generateQRCodeStr(majorCode);

			Map<String, String> dataMap = new HashMap<String, String>();
			dataMap.put("img", imgStr);
			dataMap.put("majorName", majorName);

			generateWord(outputStream, dataMap, "wordTemplate.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void genrateWordTemplate(OutputStream outputStream, Writer out, String majorCode, String majorName)
			throws WriterException {
		try {
			String imgStr = generateQRCodeStr(majorCode);

			Map<String, String> dataMap = new HashMap<String, String>();
			dataMap.put("img", imgStr);
			dataMap.put("majorName", majorName);

			generateWord(outputStream, out, dataMap, "wordTemplate.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String generateQRCodeStr(String majorCode) throws IOException, WriterException {
		BufferedImage image = QRCodeUtil.encode(majorCode, 200, 200);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(image, "JPEG", bos);

		@SuppressWarnings("restriction")
		String imgStr = new sun.misc.BASE64Encoder().encodeBuffer(bos.toByteArray());
		bos.close();
		return imgStr;
	}

	private static void generateWord(OutputStream outputStream, Writer out, Map<String, String> dataMap,
			String templateName) {
		try {
			Configuration configuration = new Configuration();

			configuration.setDefaultEncoding("UTF-8");

			configuration.setClassForTemplateLoading(WordTemplate.class, "/com/gage/print/pdf/");

			Template template = configuration.getTemplate(templateName);

			template.process(dataMap, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void generateWord(OutputStream outputStream, Map<String, String> dataMap, String templateName) {
		try {
			// 创建配置实例
			Configuration configuration = new Configuration();

			// 设置编码
			configuration.setDefaultEncoding("UTF-8");

			// ftl模板文件统一放至 com.lun.template 包下面
			configuration.setClassForTemplateLoading(WordTemplate.class, "/com/gage/print/pdf/");

			// 获取模板
			Template template = configuration.getTemplate(templateName);

			// 将模板和数据模型合并生成文件
			Writer out = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

			// 生成文件
			template.process(dataMap, out);

			// 关闭流
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}